package com.tjbank.cssys.config;

import com.tjbank.cssys.utils.JasyptUtil;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Configuration
public class EncryptablePropertyConfig {
    private static final Logger logger = LoggerFactory.getLogger(EncryptablePropertyConfig.class);

    //密文标志，以DES@***开头
    private static final String START_FLAG = "AES@";

    @Bean(name="encryptablePropertyResolver")

    public EncryptablePropertyResolver encryptablePropertyResolver() {

        return new EncryptionPropertyResolver();
    }

    public class EncryptionPropertyResolver implements EncryptablePropertyResolver {

        private String keyStr = null;

        @Override
        public String resolvePropertyValue(String value) {
            if (StringUtils.isBlank(value)) {
                return value;
            }
            //值以DES@开头的均为DES加密，需要解密throws Exception
            if (value.startsWith(START_FLAG)) {
                InputStream inputStream=null;
                try {
                    if(null==keyStr){
                        inputStream =EncryptablePropertyConfig.class.getClassLoader().getResourceAsStream("ESAPI.properties");
                        Properties properties=new Properties();
                        properties.load(inputStream);
                        keyStr = properties.getProperty("jasyptKey");
                    }

                    return resolveDESValue(value.substring(START_FLAG.length()),keyStr);
                } catch (Exception e) {
                    logger.error("密文加密异常",e.getMessage());
                }finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    } catch (IOException e) {
                        logger.error("密文加密异常",e.getMessage());
                    }
                }
            }
            //不需要解密的值直接返回
            return value;
        }

        private String resolveDESValue(String value,String keyStr) throws Exception {
            //自定义DES密文解密
            logger.info("encryptionStr value : " + value);
            String decryptionStr = JasyptUtil.decryptStr(value, keyStr);
            logger.info("decryptionStr value: " + decryptionStr);
            return decryptionStr;
        }
    }
}
